<template>
  <div class="container">
    <div style="height: 92vh;display: flex;flex-direction: column">
      <el-row>
        <el-input
            v-model="keyword"
            style="width: 200px"
            placeholder="关键字"
        />

        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="loadJsonFile">加载json文件</el-button>

      </el-row>

      <el-table :data="tableData" stripe border style="flex:1">
        <el-table-column prop="en" label="序号" width="80">
          <template #default="{row, column, $index}">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="cn" label="中文" width="140"/>

        <el-table-column prop="shortEn" label="英文简写" width="180">

          <template #default="{row, column, $index}">
            <el-input v-model="row.shortEn" placeholder="英文简写" @change="handleChangeByShortEn($event,row)"/>
          </template>
        </el-table-column>


        <el-table-column  label="引用1" width="200">
          <template #default="{row, column, $index}">
            <span >{{`R.string.${row.shortEn}`}}</span>
          </template>

        </el-table-column>
        <el-table-column  label="引用2" width="200">
          <template #default="{row, column, $index}">
            <span >{{`@string/${row.shortEn}`}}</span>
          </template>

        </el-table-column>


        <el-table-column prop="en" label="英文" width="180">
          <template #default="{row, column, $index}">
            <el-input v-model="row.en" placeholder="英文名" @change="handleChangeByInput($event,row)"/>
          </template>

        </el-table-column>

        <el-table-column prop="line" label="行数" width="80"/>
        <el-table-column prop="remark" label="备注" min-width="180"/>
      </el-table>
    </div>
    <div
        style="display: flex;align-items: center;height:8vh;background-color:white;justify-content: space-between;width: 100%">

      <el-button type="primary" @click="handleExport">导出数据</el-button>
      <el-button type="primary" @click="handleGene">生成安卓内容</el-button>

      <el-pagination background
                     v-model:page-size="pageInfo.pageSize"
                     v-model:current-page="pageInfo.pageIndex"
                     :page-sizes="[20, 50, 100]"
                     @size-change="handleCurrentChange"
                     @current-change="handleCurrentChange" layout="sizes,prev, pager, next"
                     :total="pageInfo.totalCount"/>
    </div>


  </div>

  <el-dialog v-model="exportDataDialog" title="导出数据">
    <el-input
        v-model="cacheData"
        :rows="20"
        type="textarea"
        placeholder="Please input"
    />
  </el-dialog>

  <el-dialog v-model="geneDataDialog" title="生成数据" width="75%">
    <el-row :gutter="20">

      <el-col :span="12">
        <el-input
            v-model="geneCnComputed"
            :rows="20"
            type="textarea"
            placeholder="Please input"
        />

      </el-col>
      <el-col :span="12">
        <el-input
            v-model="geneEnComputed"
            :rows="20"
            type="textarea"
            placeholder="Please input"
        />

      </el-col>

    </el-row>


  </el-dialog>


</template>
<script setup>
import {computed, onMounted, reactive, ref, toRaw} from "vue";

import saveFile from "../../查询中文/保存文件工具.js";
import {tryOnScopeDispose, useRefHistory, useStorage} from "@vueuse/core";
import _ from "lodash";


let geneDataDialog = ref(false)
let exportDataDialog = ref(false)
let keyword = ref("")

let tableData = ref([])
let pageInfo = reactive({
  pageIndex: 1,
  pageSize: 20,
  totalCount: 10,
})

//缓存的数据
let cacheData = useStorage("langData")

let geneCnComputed = computed(() => {
  let list = _.unionBy(JSON.parse(cacheData.value),item=>item.en)
  return list.map(item => ` <string name="${item.shortEn || ''}">${item.cn}</string>`).join("\n")
})
let geneEnComputed = computed(() => {
  let list = _.unionBy(JSON.parse(cacheData.value),item=>item.en)
  return list.map(item => ` <string name="${item.shortEn || ''}">${item.en}</string>`).join("\n")
})


const handleSearch = () => {
  let keywordStr = keyword.value
  let list = JSON.parse(cacheData.value)
  let result = list.filter(item => {

    return (item.cn.includes(keywordStr) || item.en.includes(keywordStr))
  }).slice(0, 20)

  tableData.value = result
}
const handleChangeByInput = (value, data) => {
  let row = toRaw(data)
  let list = JSON.parse(cacheData.value)
  list.forEach(item => {
    if (item.cn === row.cn) {
      item.en = row.en
    }
  })
  cacheData.value = JSON.stringify(list)
  getData()
}

const handleChangeByShortEn = (value, data) => {
  let row = toRaw(data)
  let list = JSON.parse(cacheData.value)
  list.forEach(item => {
    if (item.cn === row.cn) {
      item.shortEn = row.shortEn
    }
  })
  cacheData.value = JSON.stringify(list)
  getData()
}
const getData = () => {

  let finalData = undefined

  if (_.isEmpty(cacheData.value)) {
    finalData = fetch("./data.json").then(res => {
      return res.json()
    })
    console.log("文件")
  } else {
    finalData = Promise.resolve(JSON.parse(cacheData.value));
    console.log("缓存")
  }

  finalData.then(res => {
    if (_.isEmpty(cacheData.value)) {
      cacheData.value = JSON.stringify(res)
    }
    //手动分页
    pageInfo.totalCount = res.length

    tableData.value = res.slice((pageInfo.pageIndex - 1) * pageInfo.pageSize, (pageInfo.pageIndex) * pageInfo.pageSize)
  })
}
const handleCurrentChange = () => {
  getData()
}


let handleSave = () => {
  saveFile("./new.json", tableData.value, true)
}

let handleExport = () => {
  exportDataDialog.value = true
}
let handleGene = () => {
  geneDataDialog.value = true
}

import { useFileSystemAccess } from '@vueuse/core'
import { useNProgress } from '@vueuse/integrations/useNProgress'

let json=ref({
  cb:(x,y)=>{
    return x+y
  }
})

let loadJsonFile =async () => {
 await file.open()
  cacheData.value= file.data.value
  getData()
}

const file = useFileSystemAccess({
  dataType: 'Text',
    types: [{
      description: 'text',
      accept: {
        'text/plain': ['.json'  ],
      },
    }],
    excludeAcceptAllOption: true,
})

import './style.css'
const { isLoading, progress } = useNProgress( )
console.log(isLoading,progress)

onMounted(() => {
  getData()
})

</script>


<style scoped>
.container {
  width: 100%;
  display: flex;
  height: 100vh; /* 使用视窗高度作为容器高度 */
  flex-direction: column;
}


</style>
